package com.maodou.core.ui.theme

import android.content.Context
import android.content.SharedPreferences
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow

/**
 * 主题偏好设置管理器
 * 负责主题配置的持久化存储和恢复
 */
class ThemePreferences(context: Context) {
    
    private val sharedPreferences: SharedPreferences = context.getSharedPreferences(
        PREFS_NAME, Context.MODE_PRIVATE
    )
    
    private val _themeConfig = MutableStateFlow(loadThemeConfig())
    val themeConfig: StateFlow<ThemeConfig> = _themeConfig.asStateFlow()
    
    /**
     * 保存主题配置
     */
    fun saveThemeConfig(config: ThemeConfig) {
        sharedPreferences.edit().apply {
            putString(KEY_THEME_TYPE, config.themeType.name)
            putString(KEY_DARK_MODE_TYPE, config.darkModeType.name)
            putString(KEY_FONT_SIZE_TYPE, config.fontSizeType.name)
            putString(KEY_LAYOUT_DENSITY_TYPE, config.layoutDensityType.name)
            putBoolean(KEY_DYNAMIC_COLOR, config.dynamicColor)
            putBoolean(KEY_HIGH_CONTRAST, config.highContrast)
            apply()
        }
        _themeConfig.value = config
    }
    
    /**
     * 加载主题配置
     */
    private fun loadThemeConfig(): ThemeConfig {
        return try {
            ThemeConfig(
                themeType = ThemeType.valueOf(
                    sharedPreferences.getString(KEY_THEME_TYPE, ThemeType.DEFAULT.name) ?: ThemeType.DEFAULT.name
                ),
                darkModeType = DarkModeType.valueOf(
                    sharedPreferences.getString(KEY_DARK_MODE_TYPE, DarkModeType.SYSTEM.name) ?: DarkModeType.SYSTEM.name
                ),
                fontSizeType = FontSizeType.valueOf(
                    sharedPreferences.getString(KEY_FONT_SIZE_TYPE, FontSizeType.DEFAULT.name) ?: FontSizeType.DEFAULT.name
                ),
                layoutDensityType = LayoutDensityType.valueOf(
                    sharedPreferences.getString(KEY_LAYOUT_DENSITY_TYPE, LayoutDensityType.DEFAULT.name) ?: LayoutDensityType.DEFAULT.name
                ),
                dynamicColor = sharedPreferences.getBoolean(KEY_DYNAMIC_COLOR, true),
                highContrast = sharedPreferences.getBoolean(KEY_HIGH_CONTRAST, false)
            )
        } catch (e: Exception) {
            // 如果加载失败，返回默认配置
            ThemeConfig()
        }
    }
    
    /**
     * 重置为默认配置
     */
    fun resetToDefault() {
        val defaultConfig = ThemeConfig()
        saveThemeConfig(defaultConfig)
    }
    
    /**
     * 清除所有偏好设置
     */
    fun clearAll() {
        sharedPreferences.edit().clear().apply()
        _themeConfig.value = ThemeConfig()
    }
    
    /**
     * 检查是否为首次启动
     */
    fun isFirstLaunch(): Boolean {
        return !sharedPreferences.contains(KEY_THEME_TYPE)
    }
    
    /**
     * 标记已完成首次设置
     */
    fun markFirstLaunchComplete() {
        sharedPreferences.edit().putBoolean(KEY_FIRST_LAUNCH_COMPLETE, true).apply()
    }
    
    /**
     * 检查是否已完成首次设置
     */
    fun isFirstLaunchComplete(): Boolean {
        return sharedPreferences.getBoolean(KEY_FIRST_LAUNCH_COMPLETE, false)
    }
    
    /**
     * 导出配置为 JSON 字符串
     */
    fun exportConfig(): String {
        val config = _themeConfig.value
        return """
            {
                "themeType": "${config.themeType.name}",
                "darkModeType": "${config.darkModeType.name}",
                "fontSizeType": "${config.fontSizeType.name}",
                "layoutDensityType": "${config.layoutDensityType.name}",
                "dynamicColor": ${config.dynamicColor},
                "highContrast": ${config.highContrast}
            }
        """.trimIndent()
    }
    
    /**
     * 从 JSON 字符串导入配置
     */
    fun importConfig(json: String): Boolean {
        return try {
            // 简单的 JSON 解析（生产环境建议使用专业的 JSON 库）
            val themeType = extractJsonValue(json, "themeType")?.let { ThemeType.valueOf(it) } ?: ThemeType.DEFAULT
            val darkModeType = extractJsonValue(json, "darkModeType")?.let { DarkModeType.valueOf(it) } ?: DarkModeType.SYSTEM
            val fontSizeType = extractJsonValue(json, "fontSizeType")?.let { FontSizeType.valueOf(it) } ?: FontSizeType.DEFAULT
            val layoutDensityType = extractJsonValue(json, "layoutDensityType")?.let { LayoutDensityType.valueOf(it) } ?: LayoutDensityType.DEFAULT
            val dynamicColor = extractJsonBooleanValue(json, "dynamicColor") ?: true
            val highContrast = extractJsonBooleanValue(json, "highContrast") ?: false
            
            val config = ThemeConfig(
                themeType = themeType,
                darkModeType = darkModeType,
                fontSizeType = fontSizeType,
                layoutDensityType = layoutDensityType,
                dynamicColor = dynamicColor,
                highContrast = highContrast
            )
            
            saveThemeConfig(config)
            true
        } catch (e: Exception) {
            false
        }
    }
    
    /**
     * 获取配置版本（用于迁移）
     */
    fun getConfigVersion(): Int {
        return sharedPreferences.getInt(KEY_CONFIG_VERSION, 1)
    }
    
    /**
     * 设置配置版本
     */
    fun setConfigVersion(version: Int) {
        sharedPreferences.edit().putInt(KEY_CONFIG_VERSION, version).apply()
    }
    
    /**
     * 执行配置迁移
     */
    fun migrateIfNeeded() {
        val currentVersion = getConfigVersion()
        if (currentVersion < CURRENT_CONFIG_VERSION) {
            // 执行迁移逻辑
            performMigration(currentVersion, CURRENT_CONFIG_VERSION)
            setConfigVersion(CURRENT_CONFIG_VERSION)
        }
    }
    
    private fun performMigration(fromVersion: Int, toVersion: Int) {
        // 这里可以添加版本迁移逻辑
        when {
            fromVersion < 2 -> {
                // 从版本 1 迁移到版本 2 的逻辑
            }
            // 可以添加更多版本迁移逻辑
        }
    }
    
    private fun extractJsonValue(json: String, key: String): String? {
        val pattern = "\"$key\"\\s*:\\s*\"([^\"]*)\"".toRegex()
        return pattern.find(json)?.groupValues?.get(1)
    }
    
    private fun extractJsonBooleanValue(json: String, key: String): Boolean? {
        val pattern = "\"$key\"\\s*:\\s*(true|false)".toRegex()
        return pattern.find(json)?.groupValues?.get(1)?.toBoolean()
    }
    
    companion object {
        private const val PREFS_NAME = "theme_preferences"
        private const val KEY_THEME_TYPE = "theme_type"
        private const val KEY_DARK_MODE_TYPE = "dark_mode_type"
        private const val KEY_FONT_SIZE_TYPE = "font_size_type"
        private const val KEY_LAYOUT_DENSITY_TYPE = "layout_density_type"
        private const val KEY_DYNAMIC_COLOR = "dynamic_color"
        private const val KEY_HIGH_CONTRAST = "high_contrast"
        private const val KEY_FIRST_LAUNCH_COMPLETE = "first_launch_complete"
        private const val KEY_CONFIG_VERSION = "config_version"
        private const val CURRENT_CONFIG_VERSION = 1
        
        @Volatile
        private var INSTANCE: ThemePreferences? = null
        
        fun getInstance(context: Context): ThemePreferences {
            return INSTANCE ?: synchronized(this) {
                INSTANCE ?: ThemePreferences(context.applicationContext).also { INSTANCE = it }
            }
        }
    }
}

/**
 * 主题偏好设置扩展函数
 */
object ThemePreferencesExtensions {
    
    /**
     * 创建带有偏好设置的主题管理器
     */
    fun createThemeManagerWithPreferences(context: Context): ThemeManager {
        val preferences = ThemePreferences.getInstance(context)
        val manager = ThemeManager.getInstance()
        
        // 执行迁移
        preferences.migrateIfNeeded()
        
        // 加载保存的配置
        val savedConfig = preferences.themeConfig.value
        manager.applyConfig(savedConfig)
        
        return manager
    }
    
    /**
     * 同步主题管理器和偏好设置
     */
    fun syncThemeManagerWithPreferences(
        manager: ThemeManager,
        preferences: ThemePreferences
    ) {
        // 监听主题管理器的变化并保存到偏好设置
        // 注意：这需要在协程中执行
    }
    
    /**
     * 获取主题配置的摘要信息
     */
    fun ThemeConfig.getSummary(): String {
        return buildString {
            append("主题: ${ThemeUtils.getThemeTypeName(themeType)}")
            append(", 模式: ${ThemeUtils.getDarkModeTypeName(darkModeType)}")
            append(", 字体: ${ThemeUtils.getFontSizeTypeName(fontSizeType)}")
            append(", 布局: ${ThemeUtils.getLayoutDensityTypeName(layoutDensityType)}")
            if (dynamicColor) append(", 动态颜色")
            if (highContrast) append(", 高对比度")
        }
    }
    
    /**
     * 检查配置是否为默认配置
     */
    fun ThemeConfig.isDefault(): Boolean {
        val defaultConfig = ThemeConfig()
        return this == defaultConfig
    }
    
    /**
     * 检查配置是否支持当前设备
     */
    fun ThemeConfig.isSupportedOnDevice(): Boolean {
        // 检查动态颜色是否支持
        if (dynamicColor && !ThemeUtils.supportsDynamicColor()) {
            return false
        }
        return true
    }
    
    /**
     * 获取配置的兼容版本
     */
    fun ThemeConfig.getCompatibleVersion(): ThemeConfig {
        return if (isSupportedOnDevice()) {
            this
        } else {
            copy(dynamicColor = false)
        }
    }
}